package com.centaline.androidsalesblog.activities.entrust;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.sale.EsfEstateListActivity;
import com.centaline.androidsalesblog.adapter.SearchDistanceAdapter;
import com.centaline.androidsalesblog.api.sale.AutoEstateApi;
import com.centaline.androidsalesblog.api.sale.EsfEstateListApi;
import com.centaline.androidsalesblog.application.MyLocation;
import com.centaline.androidsalesblog.base.BaseEstateSearchActivity;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.iml.RecyclerViewItemOnClickListener;
import com.centaline.androidsalesblog.model.businissobject.AutoEstateBo;
import com.centaline.androidsalesblog.model.businissobject.SearchDistanceBo;
import com.centaline.androidsalesblog.model.databaseobject.EsfEstateDo;
import com.centaline.androidsalesblog.model.responseobject.AutoEstateRo;
import com.centaline.androidsalesblog.model.responseobject.EsfEstateListRo;
import com.centanet.framework.interfaces.IResponseListener;
import com.centanet.framework.widget.MaterialSearchView;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;

/**
 * 小区搜索<委托>
 * Created by Lihq on 16/3/8.
 */
public class EstateSearchActivity extends BaseEstateSearchActivity implements BDLocationListener {

    private int type;//搜索的类型
    private boolean fromUser;//是否用户主动搜索
    private ArrayList<SearchDistanceBo> distanceList = new ArrayList<>();//距离排序
    private SearchDistanceAdapter searchDistanceAdapter;
    private LocationClient locationClient;
    private LatLng latLng;

    private AutoEstateApi autoEstateApi;
    private EsfEstateListApi esfEstateListApi;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_estate_search;
    }

    @Override
    protected void findViews() {
        super.findViews();
    }

    @Override
    protected void initViews() {
        super.initViews();
        initSpeech(this);

        type = 60;

        locationClient = MyLocation.getLocationClient();
        locationClient.registerLocationListener(this);
        locationClient.start();

        searchDistanceAdapter = new SearchDistanceAdapter(this, distanceList, new RecyclerViewItemOnClickListener<SearchDistanceBo>() {
            @Override
            public void onItemOnClick(SearchDistanceBo searchDistanceBo, int tag) {
                onDistanceItemClick(searchDistanceBo, true);
            }
        });
        rv_distance.setAdapter(searchDistanceAdapter);

        initRequest();
    }


    /**
     * 点击事件
     */
    private void onDistanceItemClick(final SearchDistanceBo searchDistanceBo, boolean insert) {
        setImeVisibility(false);

        Intent intent = new Intent();
        intent.putExtra(ExtraConstant.CestCode, searchDistanceBo.getCode()).putExtra(ExtraConstant.CestName, searchDistanceBo.getTitle()).putExtra(ExtraConstant.CestAvgPriceSale, searchDistanceBo.getCestAvgPriceSale()).putExtra(ExtraConstant.CestAvgPriceRent, searchDistanceBo.getCestAvgPriceRent());
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 初始化请求api
     */
    private void initRequest() {
        autoEstateApi = new AutoEstateApi(EstateSearchActivity.class, AutoEstateRo.class, new IResponseListener<AutoEstateRo>() {
            @Override
            public void onResponse(AutoEstateRo autoEstateRo) {
                final ArrayList<AutoEstateBo> temp = autoEstateRo.getList();
                distanceList.clear();
                if (temp == null || temp.size() == 0) {
                    atv_distance.setText("没有任何相关信息");
                    atv_distance.setVisibility(View.VISIBLE);
                    searchDistanceAdapter.notifyDataSetChanged();
                } else {
                    atv_distance.setVisibility(View.GONE);
                    SearchDistanceBo searchDistanceBo;
                    for (AutoEstateBo autoEstateBo : temp) {
                        searchDistanceBo = new SearchDistanceBo();
                        searchDistanceBo.setName(autoEstateBo.getName());
                        searchDistanceBo.setCestCode(autoEstateBo.getCestCode());
                        searchDistanceBo.setCestAvgPriceSale(autoEstateBo.getEstateAvgPriceSale()==null?0:Double.parseDouble(autoEstateBo.getEstateAvgPriceSale()));
                        searchDistanceBo.setCestAvgPriceRent(autoEstateBo.getEstateAvgPriceRent()==null?0:Double.parseDouble(autoEstateBo.getEstateAvgPriceRent()));
                        distanceList.add(searchDistanceBo);
                    }
                    searchDistanceAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        esfEstateListApi = new EsfEstateListApi(EsfEstateListActivity.class, EsfEstateListRo.class,
                new IResponseListener<EsfEstateListRo>() {
                    @Override
                    public void onResponse(EsfEstateListRo esfEstateListRo) {
                        final ArrayList<EsfEstateDo> temp = esfEstateListRo.getList();
                        distanceList.clear();
                        if (temp == null || temp.size() == 0) {
                            atv_distance.setText("没有任何附近信息");
                            atv_distance.setVisibility(View.VISIBLE);
                        } else {
                            atv_distance.setVisibility(View.GONE);
                            SearchDistanceBo searchDistanceBo;
                            for (EsfEstateDo esfEstateDo : temp) {
                                searchDistanceBo = new SearchDistanceBo();
                                searchDistanceBo.setName(esfEstateDo.getName());
                                searchDistanceBo.setCestCode(esfEstateDo.getCestCode());
                                searchDistanceBo.setCestAvgPriceSale(esfEstateDo.getCestAvgPrice());
                                distanceList.add(searchDistanceBo);
                            }
                            searchDistanceAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
    }

    /**
     * 开始请求
     */
    private void startRequest(String query) {
        autoEstateApi.setKey(query);
        autoEstateApi.startRequest();

    }

    private void startDistantRequest() {
        esfEstateListApi.setStartIndex(0);
        esfEstateListApi.setPageCount(6);
        esfEstateListApi.setLatLng(latLng);
        esfEstateListApi.setType("F");
        esfEstateListApi.setRound("1000");
        esfEstateListApi.startRequest();
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        Logger.d("onQueryTextSubmit %s", query);
        fromUser = true;
        if (TextUtils.isEmpty(query))
            return true;
        startRequest(query);
        atv_distance.setVisibility(View.GONE);
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        Logger.d("onQueryTextChange %s", newText);
        fromUser = false;
        if (TextUtils.isEmpty(newText)) {
            distanceList.clear();
        } else {
            startRequest(newText);
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search, menu);
        searchView = (MaterialSearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setImeVisibility(true);
        searchView.setOnQueryTextListener(this);
        searchView.setVoiceClick(this);
        setQueryHint("请输入小区、板块 、地铁");
        textChangedImmediately();
        return true;
    }

    @Override
    protected Activity getActivityForPermissions() {
        return this;
    }

    @Override
    protected void onDestroy() {
        locationClient.unRegisterLocationListener(this);
        super.onDestroy();
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        latLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
        startDistantRequest();
        locationClient.stop();
        final int errorCode = bdLocation.getLocType();
        switch (errorCode) {
            case 61:
            case 161:
                latLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
//                setQueryHint("请输入小区、板块 、地铁");
//                textChangedImmediately();
                break;
        }
    }
}
